#include <REGX52.H>
#include <INTRINS.H>
#include "motor.h"
#include "car.h"
#include "Delay.h"
#include "Timer0.h"
#include "Blueteech.h"
#include "Infrared track.h"
#include "I2C.h"
#include "oled.h"
#define uchar unsigned char
#define  PCF8591 0x90    //PCF8591
sbit TX=P0^7;  //Trig
sbit RX=P0^6;  //Echo
sbit D1=P1^3;
sbit D2=P1^2;
sbit D3=P1^1;
sbit D4=P1^0;
unsigned char light;
unsigned char T2count,second,minute,flag,trackflag;
bit modeflag,end;
extern char mode;
extern unsigned char L_speed,R_speed,t;
void Timer2_Init(void)		//25毫秒@11.0592MHz
{
	T2MOD = 0;		//初始化模式寄存器
	T2CON = 0;		//初始化控制寄存器
	TL2 = 0x00;		//设置定时初始值
	TH2 = 0xA6;		//设置定时初始值
	RCAP2L = 0x00;		//设置定时重载值25ms
	RCAP2H = 0xA6;		//设置定时重载值
	ET2=1;
	EA=1;
	PT2=0;
	TR2 = 1;		//定时器2开始计时
}

bit ISendByte(unsigned char sla,unsigned char c)
{
   Start_I2c();              
   SendByte(sla);            
   if(ack==0)return(0);
   SendByte(c);              
   if(ack==0)return(0);
   Stop_I2c();               
   return(1);
}

unsigned char IRcvByte(unsigned char sla)
{  unsigned char c;

   Start_I2c();         
   SendByte(sla+1);      
   if(ack==0)return(0);
   c=RcvByte();          

   Ack_I2c(1);          
   Stop_I2c();          
   return(c);
}

void main(void)
{
	OLED_Init();
	Delay(100);
	OLED_CLEAR();			//清屏
	Delay(100);
	Timer0_Init();
	Timer2_Init();
	Uart_Init();
	IT0=1;IT1=1;           //外部中断初始化
	EA=1;
	PX0=1;PX1=0;
//	P1_4=0;
	while(1)
	{  
		if(T2count%20==0){	
		OLED_ShowString(0,0,"timesum:"); 
	 	OLED_ShowNum(64,0,minute,1,16); 
		OLED_ShowString(75,0,":"); 
		OLED_ShowNum(90,0,second,2,16);
		OLED_ShowString(0,2,"light:");
		OLED_ShowNum(50,2,light,3,16); 
		OLED_ShowNum(0,4,L_speed,2,16);
		OLED_ShowNum(30,4,R_speed,2,16);
		OLED_ShowNum(100,4,end,1,16);
		OLED_ShowNum(70,4,mode,1,16);			//循迹时会停止刷新 蓝牙时正常刷新
		OLED_ShowString(0,6,"Delay:");
		OLED_ShowNum(50,6,t,2,16);
		}
		
		if(mode==1){
			Track();
		}	  
	}

} 	

	

void Timer2_Routine() interrupt 5
{	  
    TF2=0;
	RCAP2L = 0x00;		//设置定时重载值25ms
	RCAP2H = 0xA6;		//设置定时重载值
	T2count++;
	T2count%=80;
	ISendByte(PCF8591,0x41);  //光照强度检测
	light=IRcvByte(PCF8591);
if(light<150&&light>10&&modeflag==0&&end==0){
	flag++;
	if(flag>=2){  //50ms反应连续检查两次  不要让线挡住光感！！！
	mode=1;   		//进入循迹mode
	modeflag=1;		//起步后检测
	T2count=0;	
	second=0;
	minute=0;
	}
}	

if(light<150&&light>10&&modeflag==1){	//现场设置阈值！！！
	if(second>=5||minute>=1){						//间隔5s再加入结束光感判断
//	trackflag++;								
//	if(trackflag>=2){			
		mode=0;				//退出循迹
		trackflag=0;	
		end=1;    				//一次性红外循迹 蓝牙清零
		modeflag=0;
		D1=1;D2=1;D3=1;D4=1;
		car_back();
		Delay(10);
		car_stop();
//		}	
	}
}
if(mode==1){						//仅计循迹时间
	if(T2count>=40){
		T2count=0;					//时钟计时
		second++;
	}
	if(second==60){
		second=0;
		minute++;
		}
	}
}


